#
# import matplotlib.pyplot as plt
# import matplotlib.dates as mdates
# import datetime
#
# file_path = "received_from_server/Sleepv3_SLS_20250917-005605.txt"
#
# session_start = None
# session_end = None
# interval = 30
# sleep_data = []
#
# with open(file_path, "r", encoding="utf-8") as f:
#     for line in f:
#         line = line.strip()
#         if not line or line.startswith("%"):
#             if "Session Start Time" in line:
#                 session_start = line.split(":", 1)[1].strip()
#             elif "Session End Time" in line:
#                 session_end = line.split(":", 1)[1].strip()
#             elif "Interval" in line:
#                 interval = int(line.split(":", 1)[1].strip().replace("s", "").strip())
#             continue
#
#         parts = line.split()
#         if len(parts) == 2:
#             quality, stage = map(int, parts)
#             sleep_data.append((quality, stage))
#
# start_time = datetime.datetime.strptime(session_start, "%Y-%m-%d %H:%M:%S")
# end_time = datetime.datetime.strptime(session_end, "%Y-%m-%d %H:%M:%S")
#
# # x轴时间序列
# times = [start_time + datetime.timedelta(seconds=i * interval) for i in range(len(sleep_data))]
#
# # y轴：不同睡眠阶段高度相差20
# y_values = [s[1] * 20 for s in sleep_data]
#
# # 颜色映射
# color_map = {
#     0: "green",
#     1: "lightgreen",
#     2: "yellow",
#     3: "red",
#     4: "black"
# }
# colors = [color_map[q] for q, _ in sleep_data]
#
# # 绘图
# plt.figure(figsize=(15, 6))
# for i in range(1, len(times)):
#     plt.plot(times[i-1:i+1], y_values[i-1:i+1], color=colors[i], linewidth=1.5)
#
# # y轴
# plt.yticks([0, 20, 40, 60, 80], ["Unspecified", "Deep sleep", "Light sleep", "REM Sleep", "Awake"])
# plt.ylim(-5, 85)
#
# # x轴时间格式化为 年-月-日 时:分
# plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
# plt.gca().xaxis.set_major_locator(mdates.HourLocator())  # 每小时一个主刻度
# plt.gca().xaxis.set_minor_locator(mdates.MinuteLocator(byminute=range(0,60,30)))  # 每30分钟一个副刻度
#
# plt.xlim(start_time, end_time)
#
# plt.xlabel("Time")
# plt.ylabel("Sleep stage")
# plt.title("Sleep stage change chart")
# plt.grid(alpha=0.3)
# # 在图下方加上 start 和 end 时间
# start_label = start_time.strftime("%m-%d %H:%M")
# end_label = end_time.strftime("%m-%d %H:%M")
#
# plt.text(start_time, -10, f"Start: {start_label}", ha="left", va="top", fontsize=10, color="blue")
# plt.text(end_time, -10, f"End: {end_label}", ha="right", va="top", fontsize=10, color="blue")
#
# plt.tight_layout()
# plt.savefig("sleep_plot.png", dpi=300)
# plt.show()
#
#
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

def generate_png(txt_path):
    print(f"[sleepPng] 开始生成 PNG: {txt_path}")
    file_path = txt_path
    session_start = None
    session_end = None
    interval = 30
    sleep_data = []

    with open(file_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("%"):
                if "Session Start Time" in line:
                    session_start = line.split(":", 1)[1].strip()
                elif "Session End Time" in line:
                    session_end = line.split(":", 1)[1].strip()
                elif "Interval" in line:
                    interval = int(line.split(":", 1)[1].strip().replace("s","").strip())
                continue
            parts = line.split()
            if len(parts) == 2:
                quality, stage = map(int, parts)
                sleep_data.append((quality, stage))

    if not session_start or not session_end:
        print("[sleepPng] 警告: 未检测到 session_start 或 session_end")
    else:
        print(f"[sleepPng] Session 开始: {session_start}, 结束: {session_end}, 数据点数量: {len(sleep_data)}")

    start_time = datetime.datetime.strptime(session_start, "%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(session_end, "%Y-%m-%d %H:%M:%S")
    times = [start_time + datetime.timedelta(seconds=i*interval) for i in range(len(sleep_data))]
    y_values = [s[1]*20 for s in sleep_data]

    color_map = {0:"green",1:"lightgreen",2:"yellow",3:"red",4:"black"}
    colors = [color_map[q] for q,_ in sleep_data]

    plt.figure(figsize=(15,6))
    for i in range(1,len(times)):
        plt.plot(times[i-1:i+1], y_values[i-1:i+1], color=colors[i], linewidth=1.5)

    plt.yticks([0,20,40,60,80], ["Unspecified","Deep sleep","Light sleep","REM Sleep","Awake"])
    plt.ylim(-5,85)
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
    plt.gca().xaxis.set_major_locator(mdates.HourLocator())
    plt.gca().xaxis.set_minor_locator(mdates.MinuteLocator(byminute=range(0,60,30)))
    plt.xlim(start_time,end_time)
    plt.xlabel("Time")
    plt.ylabel("Sleep stage")
    plt.title("Sleep stage change chart")
    plt.grid(alpha=0.3)
    start_label = start_time.strftime("%m-%d %H:%M")
    end_label = end_time.strftime("%m-%d %H:%M")

    plt.text(start_time, -10, f"Start: {start_label}", ha="left", va="top", fontsize=10, color="blue")
    plt.text(end_time, -10, f"End: {end_label}", ha="right", va="top", fontsize=10, color="blue")
    # png_path = "./received_from_server/sleep_plot.png"
    png_path = f"./received_from_server/sleep_plot_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.png"
    plt.tight_layout()
    plt.savefig(png_path, dpi=300)
    plt.close()
    print(f"[sleepPng] PNG 已保存: {png_path}")
    return png_path
